<template>
    <view>
        <context-holder />
        <a-page-header title="LLog" sub-title="v1.0.0">
            <!-- <template #extra>
                <a-button @click="switchMode" type="primary">{{ logMode }}</a-button>
            </template> -->
            <!--增加搜索-->
        </a-page-header>
        <AntdZh>
            <a-table :scroll="{ x: 2000 }" :columns="customColumns" :data-source="dataSource" :expend-key="id"
                :loading="loading" :pagination="pagination" @change="handleTableChange">
                <template #customFilterDropdown="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }">
                    <view v-if="column.dataIndex == 'reqSource'">
                        <div style="padding: 8px;width: 200px;height: 65px;">
                        <a-input-search v-model:value="queryParams.operatorId" placeholder="请输入用户ID"
                            style="width: 200px" @search="doSourceReq()" />
                        <a-button @click="doSourceReq(null)" type="primary" size="small" style="top:10px;width: 90px">
                            重置
                        </a-button>
                    </div>
                    </view>
                    <view v-else-if="column.dataIndex == 'params'">
                        <div style="padding: 8px;width: 200px;height: 65px;">
                        <a-input-search v-model:value="queryParams.reqKey" placeholder="请输入查询关键词"
                            style="width: 200px" @search="doParamsReq()" />
                        <a-button @click="doParamsReq(null)" type="primary" size="small" style="top:10px;width: 90px">
                            重置
                        </a-button>
                    </div>
                    </view>
                    
                </template>
                <template #customFilterIcon="{ column, filtered }">
                    <search-outlined v-if="column.dataIndex == 'reqSource' || column.dataIndex == 'params'"
                        :style="{ color: filtered ? '#108ee9' : undefined }" />
                    <FilterFilled v-else :style="{ color: filtered ? '#108ee9' : undefined }"></FilterFilled>
                </template>
                <!--自定义表头-->
                <template #headerCell="{ column }">
                    <template v-if="column.dataIndex === 'method'">
                        <span>
                            接口方法
                        </span>
                    </template>
                </template>
                <template #bodyCell="{ column, record }">
                    <template v-if="column.dataIndex === 'params'">
                        <a-popover title="请求参数">
                            <template #content>
                                <JsonEditor style="width: 300px;" v-model:value="record.params" readOnly>
                                </JsonEditor>
                            </template>
                            {{ record.params }}
                        </a-popover>

                    </template>
                    <template v-else-if="column.dataIndex === 'returnData'">
                        <view v-if="record.status == 1">
                            <a-popover title="响应数据">
                                <template #content>
                                    <JsonEditor style="width: 300px;" v-model:value="record.returnData" readOnly>
                                    </JsonEditor>
                                </template>
                                {{ record.returnData }}
                            </a-popover>
                        </view>
                        <view v-else>
                            <a-button @click="showLog(record.id)">异常堆栈</a-button>
                        </view>


                    </template>
                    <template v-else-if="column.dataIndex === 'status'">
                        <!--执行状态-->
                        <a-tag color="green" v-if="record.status">成功</a-tag>
                        <a-tag color="red" v-else>失败</a-tag>
                        <!--请求用时-->
                        <a-tag color="green" v-if="record.totalTime <= 100">{{ record.totalTime }}ms</a-tag>
                        <a-tag color="orange" v-else-if="record.totalTime <= 300">{{ record.totalTime }}ms</a-tag>
                        <a-tag color="red" v-else>{{ record.totalTime }}ms</a-tag>


                    </template>
                    <template v-else-if="column.dataIndex === 'method'">
                        <a-tag color="green" v-if="record.action == 'CREATE'">新建</a-tag>
                        <a-tag color="#f50" v-else-if="record.action == 'DELETE'">删除</a-tag>
                        <a-tag color="orange" v-else-if="record.action == 'UPDATE'">更新</a-tag>
                        <a-tag color="blue" v-else-if="record.action == 'READ'">查询</a-tag>
                        <a-tooltip>
                            <template #title> {{ record.apiName }}</template>
                            {{ record.method }}
                        </a-tooltip>

                    </template>
                    <template v-else-if="column.dataIndex === 'module'">
                        <view v-if="record.module != '' && record.module != undefined && record.module != null">
                            {{ record.module }}
                        </view>
                        <view v-else>
                            未分类请求
                        </view>


                    </template>
                    <template v-else-if="column.dataIndex === 'reqSource'">
                        <a-tag v-if="record.operatorId == 0">无登录态</a-tag>
                        <a-tag v-else color="green">用户:{{ record.operatorId }}</a-tag>
                        <!--请求IP-->
                        <a-tag v-if="record.clientIp == '0:0:0:0:0:0:0:1'">本地请求</a-tag>
                        <a-tag color="cyan" v-else>{{ record.clientIp }}</a-tag>

                    </template>
                </template>
            </a-table>
        </AntdZh>
        <!--悬浮按钮-->
        <!-- <a-float-button-group trigger="hover" type="primary" :style="{ right: '30px' }">
            <template #icon>
                <CustomerServiceOutlined />
            </template>
            <a-float-button />
            <a-float-button>
                <template #icon>
                    <CommentOutlined />
                </template>
            </a-float-button>
        </a-float-button-group> -->
        <!--异常堆栈-->
        <a-drawer size="large" v-model:open="stackShow" class="custom-class" root-class-name="root-class-name"
            :root-style="{ color: 'blue' }" style="color: red" title="异常信息" placement="right">
            <JsonEditor  width="700" height="800" v-model:value="consoleLog" readOnly>
            </JsonEditor>
        </a-drawer>
    </view>
</template>
<script setup>
import AntdZh from '../AntdZh/index.vue';
import JsonEditor from '../JsonEditor/index.vue';
//   import AntdZh from '@/components/AntdZh/index.vue';
import { computed, ref, reactive, defineProps, defineEmits } from 'vue'
import { Drawer as ADrawer, Affix as AAffix, PageHeader as APageHeader, Tabs as ATabs, TabPane as ATabPane, Descriptions as ADescriptions, DescriptionsItem as ADescriptionsItem, FloatButtonGroup as AFloatButtonGroup, FloatButton as AFloatButton, message, InputSearch as AInputSearch, Button as AButton, Table as ATable, Tag as ATag, Tooltip as ATooltip, Popover as APopover } from 'ant-design-vue'
const [messageApi, contextHolder] = message.useMessage();
import { SearchOutlined, FilterFilled, CustomerServiceOutlined, CommentOutlined } from '@ant-design/icons-vue';
import axios from 'axios';
import { columns, defaultQueryParams } from './index';
const customColumns = ref(JSON.parse(JSON.stringify(columns)));
const queryParams = ref(defaultQueryParams);
const total = ref(0);
const dataSource = ref([])
const loading = ref(false)
const stackShow = ref(false);
const logMode = ref('微服务')
const consoleLog = ref('')
// const DEV_API = '/dev-api';
const DEV_API = '';
const pagination = computed(() => ({
    total: total.value,
    current: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
}));
function showLog(id) {
    stackShow.value = true;
    consoleLog.value = ''
    axios({
        url: DEV_API + '/monitor/logs/' + id + '/console',
        method: 'get'
    }).then(res => {

        consoleLog.value = res.data;
    })
}
// 切换模式
function switchMode() {
    if (logMode.value == '单体应用') {
        logMode.value = '微服务'
        customColumns.value = JSON.parse(JSON.stringify(columns));
    } else {
        logMode.value = '单体应用'
        customColumns.value.splice(0, 1)
    }
}
// 异常表单
function handleError(result) {
    messageApi.error("请求异常");
}
// 执行查询
function doSourceReq(e){
    if(e === null){
        queryParams.value.operatorId = undefined;
    }
    queryParams.value.pageNum = 1;
    reqLogs();
}
function doParamsReq(e){
    if(e === null){
        queryParams.value.reqKey = undefined;
    }
    queryParams.value.pageNum = 1;
    reqLogs();
}
// 获取用户日志模块
function reqModules() {
    axios({
        url: DEV_API + '/monitor/log/modules',
        method: 'get'
    }).then(res => {
        let modules = res.data;
        // console.log(modules)
        let filters = []
        var len = modules.length;
        for (var i = 0; i < len; i++) {

            if (modules[i] != '') {
                let obj = {
                    text: modules[i],
                    value: modules[i]
                }
                filters.push(obj)

            }
        }
        for (i = 0; i < customColumns.value.length; i++) {
            // 修改模块内容
            if (customColumns.value[i].dataIndex == 'module') {
                customColumns.value[i].filters = filters
            }
        }

    })
}
// 获取用户微服务模块


function handleTableChange(page, filters, sorted) {
    if (sorted.order === "ascend") {
        queryParams.value.order = 'ASC'
    } else {
        queryParams.value.order = 'DESC'
    }

    queryParams.value.pageSize = page.pageSize;
    queryParams.value.pageNum = page.current;

    var modules = filters.module;
    console.log(modules)
    queryParams.value.modules = modules;
    var actions = filters.method;
    console.log(actions)
    queryParams.value.actions = actions;
    var statuses = filters.status;
    console.log(statuses)
    queryParams.value.statuses = statuses;
    reqLogs();
}

function reqLogs() {
    loading.value = true;
    axios({
        url: DEV_API + '/monitor/logs',
        params: queryParams.value,
        method: 'get'
    }).then(res => {
        //console.log(res)
        loading.value = false;
        dataSource.value = res.data.content;
        total.value = res.data.totalElements;
    }).catch(function (error) {
        loading.value = false;
        handleError(error)
    })

}
reqModules();
reqLogs();
</script>